"""**7.2 sqlalchemy ORM-创建数据**"""
#连接数据库
from sqlalchemy import create_engine, Column, Integer, String, Text, Float, DateTime
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# 创建数据库连接
engine = create_engine('mysql+mysqlconnector://root:123456@127.0.0.1:3306/django-web')
# 创建会话
Session = sessionmaker(bind=engine)
session = Session()
print("打印出session:",session)
# 创建基类
Base = declarative_base()
print("打印出Base:",Base)
# 定义模型
class Article(Base):
    #映射表名
    __tablename__ = 'blog_article'
    '''标题 title,内容 content,作者 author,价格 price,发布日期 pub_date,状态 status'''
    id = Column(Integer, primary_key=True)
    title = Column(String(200))
    content = Column(Text)
    author = Column(String(100))
    price = Column(Float)
    pub_date = Column(DateTime)
    status = Column(Integer)
    def __repr__(self):
        return f"<Article(title='{self.title}', author='{self.author}')>"

#创建数据
#创建一个Article对象
article = Article(title="Python 编程", content="Python 是一种高级编程语言", author="John Doe", price=29.99, pub_date="2024-07-01", status=1)
#将对象添加到会话中
session.add(article)
#提交会话，将数据写入数据库
session.commit()
#关闭会话
session.close()
print("数据创建成功")

#刀郎演唱会
#创建一个Article对象
article = Article(title="刀郎演唱会", content="刀郎演唱会是一首经典的歌曲", author="John Doe", price=29.99, pub_date="2024-07-01", status=1)
article2 = Article(title="刀郎演唱会2", content="刀郎演唱会是一首经典的歌曲2", author="John Doe", price=29.99, pub_date="2024-07-01", status=1)
article3 = Article(title="刀郎演唱会3", content="刀郎演唱会是一首经典的歌曲3", author="John Doe", price=29.99, pub_date="2024-07-01", status=1)
#将对象添加到会话中
session.add(article)
session.add(article2)
session.add(article3)
#提交会话，将数据写入数据库
session.commit()
#关闭会话
session.close()
print("数据创建成功")

